package org.lk.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.lk.reggie.common.R;
import org.lk.reggie.dto.DishDto;
import org.lk.reggie.dto.SetmealDto;
import org.lk.reggie.entity.Dish;
import org.lk.reggie.entity.DishFlavor;
import org.lk.reggie.service.CategoryService;
import org.lk.reggie.service.DishFlavorService;
import org.lk.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/dish")
public class DishController
{
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;


    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto)
    {
        dishService.saveWithFlavor(dishDto);
        return R.success("success");
    }


    @GetMapping("/page")
    public R<Page> getAllDish(@RequestParam("page") Integer currentPage, @RequestParam Integer pageSize, String name)
    {
        // 分页构造器
        Page<Dish> pageInfo = new Page(currentPage, pageSize);
        Page<DishDto> pageDto = new Page<>();

        // 查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);

        dishService.page(pageInfo, queryWrapper);

        // 对象拷贝 从 pageInfo 到 pageDto
        BeanUtils.copyProperties(pageInfo, pageDto, "records");

        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = new ArrayList<>();

        for (Dish dish:
             records)
        {
            Long categoryId = dish.getCategoryId();
            String categoryName = categoryService.getById(categoryId).getName();
            DishDto dto = new DishDto();

            BeanUtils.copyProperties(dish, dto);

            dto.setCategoryName(categoryName);

            list.add(dto);
        }

        pageDto.setRecords(list);

        return R.success(pageDto);
    }



    @GetMapping("/{id}")
    public R<DishDto> getDishCaseId(@PathVariable Long id)
    {
        DishDto dishById = dishService.getDishById(id);
        if (dishById != null)
            return R.success(dishById);
        return R.error("error");
    }


    @PutMapping
    public R<String> updateDish(@RequestBody DishDto dishDto)
    {
        boolean b = dishService.myUpdateDish(dishDto);
        if (b)
        {
            // 更新成功后清理缓存
            // 菜品缓存名称为 dish_categoryId
            String key = "dish_" + dishDto.getCategoryId();
            redisTemplate.delete(key);

            return R.success("success");
        }

        return R.error("error");
    }


    @PostMapping("/status/{status}")
    public R<String> DishStatus(@RequestParam String ids, @PathVariable Integer status)
    {
        boolean suspend = dishService.suspend(ids, status);
        if (suspend)
            return R.success("success");
        return R.error("error");
    }


    @DeleteMapping()
    public R<String> dishRemove(@RequestParam Long ids)
    {
        boolean b = dishService.deleteDish(ids);
        if (b)
            return R.success("success");
        return R.error("error");
    }


//    @GetMapping("/list")
//    public R<List<Dish>> getDishByCategoryId(@RequestParam Long categoryId)
//    {
//        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Dish :: getCategoryId, categoryId);
//        queryWrapper.eq(Dish :: getStatus, 1);
//        queryWrapper.orderByAsc(Dish :: getSort).orderByAsc(Dish :: getUpdateTime);
//        List<Dish> list = dishService.list(queryWrapper);
//
//        if (list.size() > 0)
//            return R.success(list);
//        else
//            return R.error("该分类下无菜品");
//    }

    @GetMapping("/list")
    public R<List<DishDto>> getDishByCategoryId(@RequestParam Long categoryId)
    {
        // 动态设置 key
        String key = "dish" + categoryId;

        // 先从 redis 获取缓存数据
        List<DishDto> res = (List<DishDto>) redisTemplate.opsForValue().get(key);
        // 如果存在，直接返回缓存数据
        if (res != null && res.size() > 0)
        {
            return R.success(res);
        }
        // 不存在查询数据库，并将查询到的数据缓存到 redis
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish :: getCategoryId, categoryId);
        queryWrapper.eq(Dish :: getStatus, 1);
        queryWrapper.orderByAsc(Dish :: getSort).orderByAsc(Dish :: getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);
        res = new ArrayList<>();
        for (Dish d :
                list)
        {
            DishDto dto = new DishDto();
            BeanUtils.copyProperties(d, dto);
            LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(DishFlavor :: getDishId, d.getId());
            List<DishFlavor> list1 = dishFlavorService.list(queryWrapper1);
            dto.setFlavors(list1);
            res.add(dto);
        }

        if (res.size() > 0)
        {
            redisTemplate.opsForValue().set(key, res, 60, TimeUnit.MINUTES);
            return R.success(res);
        }

        else
            return R.error("该分类下无菜品");
    }

}
